﻿/****************************************************************************
Copyright (c) 2014-2015 凌惊雪 微信:Lingjingxue 邮箱:lingjingxue@sina.com QQ:271487457

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        佛祖保佑    永无BUG    永不修改
佛曰：
          写字楼里写字间，写字间里程序员；
          程序人员写程序，又拿程序换酒钱。
          酒醒只在网上坐，酒醉还来网下眠；
          酒醉酒醒日复日，网上网下年复年。
          但愿老死电脑间，不愿鞠躬老板前；
          奔驰宝马贵者趣，公交自行程序员。
          别人笑我忒疯癫，我笑自己命太贱；
          不见满街漂亮妹，哪个归得程序员？
****************************************************************************/

using UtilPublic.ServerLoger;
using ServerGame.Service;
using System;
using System.Threading;
using ServerGame.Manager;
using ServerBase.Service;
using ServerBase.Config;
using ServerPublic.Data;
using ServerPublic.Manager;
using ServerPublic.DataBaseMysql;
using System.Threading.Tasks;
using ServerGame.Data;
using ServerBase.LunarSocket;
using ServerBase.Protocol;
using UtilPublic.Http;

namespace ServerGame
{
    /// <summary>
    /// 主守护进程
    /// </summary>
    internal class Program
    {
        /// <summary>
        /// 主程序
        /// </summary>
        /// <param name="args"></param>
        private static void Main(string[] args)
        {
            BaseServerInfo.ServerType = EServerType.游戏;

            if (!BaseProgram.PubMain1(args)) { return; }

            #region HPSocket服务器

            BaseAppServer.Setup();

            #region 服务器事件

            //// 连接进入
            //BaseAppServer.AppServer.OnAccept += (sender, id, client) =>
            //{
            //    loger.Debug("接收到连接: " + id);

            //    if (BaseAppServer.AllSessions.TryGetValue(id, out var session))
            //    {
            //        session.Connected = true;
            //    }
            //    else
            //    {
            //        session = new LunarSession(sender, id);
            //        BaseAppServer.AllSessions.TryAdd(id, session);
            //    }

            //    session.SendImm(new G2C_Login_Connect()
            //    {
            //    });

            //    return HandleResult.Ok;
            //};

            //// 不需要在绑定OnReceive事件
            //// 这里解析请求体事件的packet就是PacketDataReceiveAdapter.ParseRequestBody()返回的数据
            //BaseAppServer.AppServer.OnParseRequestBody += (sender, id, requestInfo) =>
            //{
            //    if (requestInfo.ProtocolID == 0)
            //    {
            //        loger.Warn("收到空消息");
            //    }

            //    if (BaseAppServer.AllSessions.TryGetValue(id, out var session))
            //    {
            //        if (BaseDispatch.ListProtocolImm.Contains(requestInfo.ProtocolID))
            //        {
            //            BaseDispatch.ProcessMessageImm(session, requestInfo);
            //        }
            //        else
            //        {
            //            session.ListReq.Enqueue(requestInfo);
            //        }
            //    }
            //    return HandleResult.Ok;
            //};

            //// 连接关闭
            //BaseAppServer.AppServer.OnClose += (sender, id, operation, code) =>
            //{
            //    loger.Debug($"连接断开 OnClose({id}) -> operation: {operation}, code: {code}");

            //    if (BaseAppServer.AllSessions.TryGetValue(id, out var session))
            //    {
            //        //玩家
            //        if (DataGame.GetPlayer(session.Puid, out var player))
            //        {
            //            loger.Info($"玩家断线: PUID: {player.Id} 账号: {player.DaBasic.Name}");

            //            player.PlayerLoginOut();
            //        }
            //        session.Connected = false;
            //        BaseAppServer.AllSessions.TryRemove(id, out _);
            //    }

            //    return HandleResult.Ok;
            //};
            #endregion

            if (!BaseAppServer.Start())
            {
                Console.ReadKey();
                return;
            }

            #endregion

            BaseProgram.PubMain2();

            #region 启动服务器后执行服务器数据初始化

            OnServerStart();

            #endregion 启动服务器后执行服务器数据初始化

            //添加读取指令的线程
            BaseServerInfo.ListTasks.Add(Task.Run(() => { GameCmds.TaskCmds(); }));

            #region Http服务
            //启动

            //var HttpServer = new Server();
            //HttpServer.SetPort(BaseServerInfo.PortHttpServer);
            //HttpServer.AddHandler(new HttpHandler()
            //{
            //    Method = "POST",
            //    Path = "/gm",
            //    Handler = GmManager.HandlerGm,
            //});
            //HttpServer.Run();
            //loger.Info($"HttpServer Start {BaseServerInfo.PortHttpServer}");

            AHttpServer.HttpStart(BaseServerInfo.PortHttpServer, HttpMgr.HandlerAsync);
            //AHttpServer.HttpStart(BaseServerInfo.PortHttpServer, GmManager.HandlerGm);

            #endregion

            #region 进入主循环

            while (true)
            {
                System.Threading.Thread.CurrentThread.Join(BaseServerInfo.ServerHeartbeat);
                try
                {
                    LoopServer.Loop();
                }
                catch (Exception ex)
                {
                    loger.Fatal("服务器错误", ex);
                }
            }

            #endregion 进入主循环
        }

        /// <summary>
        /// 启动服务器后执行服务器数据初始化
        /// </summary>
        public static void OnServerStart()
        {
            //根据服务器ID和分区设置窗口标题
            Console.Title = BaseServerInfo.ServerZone;

            //注册消息
            Dispatcher.RegisterEventHandlerAll();

            //注册GM指令
            GmManager.RegisterGmEventHandler();

            //创建数据库
            MysqlFunction.MysqlCreateTable();

            //读取服务器数据
            PubDataServerMgr.LoadData();

            //全局数据加载
            DataGame.LoadAll();

            //负载
            ServerMgrGame.LoadUpdate();

            //服务器列表
            PubDataLoadMgr.获取负载列表游戏服务器();

            //初始化走马灯
            NoticeMgr.ResetConfNoticeRolling();

            //循环注册
            LoopServer.LoopServerRegister();
            LoopPlayer.LoopPlayerRegister();

            //显示服务器运行模式
            BaseServerInfo.SetRunMode();

        }
    }
}